package net.qqxh.resolve2text.impl;


import net.qqxh.resolve2text.File2TextResolve;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import org.springframework.stereotype.Component;

import java.io.*;

@Component
public class Pdf2TextResolve implements File2TextResolve {
    private static String TYPE = "pdf";

    @Override
    public String resolve(File file) throws IOException {
        String text = "";
        PDDocument pdfdoc = null;
        InputStream is = null;
        try {
            is = new FileInputStream(file);
            pdfdoc = PDDocument.load(is);
            PDFTextStripper stripper = new PDFTextStripper();
            text = stripper.getText(pdfdoc);
        } catch (IOException e) {
            throw e;
        } finally {
            try {
                if (pdfdoc != null) {
                    pdfdoc.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (is != null) {
                    is.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return text;
    }

    @Override
    public String getType() {
        return TYPE;
    }
}
